package com.kming.crypto;

import com.kming.crypto.annotation.EncryptBody;
import com.kming.crypto.config.CryptoConfig;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Optional;

/**
 * responseBody数据加密，如果类或方法上有@EncryptBody注解的话
 * 2022/5/13 11:46
 */
@RestControllerAdvice
public class EncryptResponseBody implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 判断方法或类上是否有@EncryptBody注解
        return returnType.hasMethodAnnotation(EncryptBody.class)
                || returnType.getContainingClass().isAnnotationPresent(EncryptBody.class);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        return encryptData(body, returnType);
    }

    protected Object encryptData(Object body, MethodParameter returnType){
        // 从方法或类上获取@EncryptBody注解
        EncryptBody encrypt = Optional
                .ofNullable(returnType.getMethodAnnotation(EncryptBody.class))
                .orElse(returnType.getContainingClass().getAnnotation(EncryptBody.class));
        return CryptoConfig.getEncrypt(encrypt.value()).encrypt(body);
    }

}
